package com.yf.cmw.dao.buss;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;

import com.base.common.http.model.DownLoadModel;
import com.base.common.util.StringHandler;
import com.base.common.util.StringUtils;
import com.base.common.util.date.DateUtil;
import com.yf.cmw.constant.BussConstant;
import com.yf.cmw.dao.BaseDao;
import com.yf.cmw.entity.DownloadLogEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * 下载日志表
 *
 * @author chengmingwei
 * @date 2018-08-19 11:58
 */
public class DownloadLogDao extends BaseDao {
    public static final String TAB_NAME = "APP_DownloadLog";

    public DownloadLogDao(Context context) {
        super(context);
    }

    @Override
    protected String getCreateTabSql() {
        StringBuilder sbSql = new StringBuilder();
        sbSql.append("create table ").append(TAB_NAME).append("(")
                .append("_id  INTEGER PRIMARY KEY AUTOINCREMENT,")
                .append("btype INTEGER,")
                .append("fname VARCHAR(60),")
                .append("lpath VARCHAR(150),")
                .append("durl VARCHAR(150),")
                .append("xstatus INTEGER,")
                .append("sourceId INTEGER,")
                .append("sstatus INTEGER,")
                .append("endTime VARCHAR(20),")
                .append("createTime VARCHAR(20),")
                .append("finishTime VARCHAR(20),")
                .append("sourceFileName VARCHAR(100),")
                .append("address VARCHAR(150),")
                .append("remark VARCHAR(255)")
                .append(")");
        return sbSql.toString();
    }

    @Override
    protected String dropTabSql() {
        return null;
    }



    public DownloadLogEntity save(DownLoadModel downLoadModel){
        Long sourceId = downLoadModel.getSourceId();
        DownloadLogEntity obj =  getBySourceId(sourceId);
        boolean isAdd = false;
        if(null == obj){
            obj = new DownloadLogEntity();
            isAdd = true;
        }
        obj.setSourceId(downLoadModel.getSourceId());
        obj.setAname(downLoadModel.getAname());
        obj.setSourceFileName(downLoadModel.getSourceFileName());
        obj.setFileSize(downLoadModel.getFileSize());
        obj.setAddress(downLoadModel.getAddress());
        obj.setLpath(downLoadModel.getLpath());
        obj.setBtype(BussConstant.BTYPE_1);
        Long id = null;
        if(isAdd){
            id = save(obj);
            obj.setId(id);
        }else{
            id = (long)update(obj);
        }
        return obj;
    }
    /**
     * 保存下载日志记录
     *
     * @param obj
     * @return
     */
    public Long save(DownloadLogEntity obj) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put("sourceId", obj.getSourceId());
        values.put("btype", obj.getBtype());
        values.put("fname", obj.getFname());
        values.put("durl", obj.getDurl());
        values.put("xstatus", obj.getXstatus());
        values.put("createTime", obj.getCreateTime());
        values.put("endTime", obj.getEndTime());
        values.put("sourceFileName", obj.getSourceFileName());
        values.put("address", obj.getAddress());
        values.put("aname", obj.getAname());
        values.put("fileSize", obj.getFileSize());
        long id = database.insert(TAB_NAME, null, values);
        obj.setId(id);
        database.close();
        return id;
    }


    /**
     * 删除机器日志
     * @param sourceId 开始日期
     * @return 返回删除的行数
     */
    public int delete(Long sourceId) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        String selection = null;
        StringBuilder sbWhere = new StringBuilder();
        if (!StringUtils.isEmpty(sourceId)) {
            sbWhere.append(" sourceId = '" + sourceId + "' ");
        }

        if (null != sbWhere && sbWhere.length() > 0) {
            selection = sbWhere.toString();
        }

        int result = database.delete(TAB_NAME, selection, null);
        database.close();
        return result;
    }

    /**
     * 删除机器日志
     *
     * @param startDate 开始日期
     * @param endDate   截止日期
     * @return 返回删除的行数
     */
    public int delete(String startDate, String endDate) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        String selection = null;
        StringBuilder sbWhere = new StringBuilder();
        if (StringHandler.isValidStr(startDate)) {
            sbWhere.append(" createTime >= '" + startDate + "' ");
        }

        if (StringHandler.isValidStr(endDate)) {
            String sigin = " ";
            if (null != sbWhere && sbWhere.length() > 0) {
                sigin = " and ";
            }
            endDate = DateUtil.getPreDateStr("dd", endDate, -1);

            sbWhere.append(sigin).append(" createTime < '" + endDate + "' ");
        }

        if (null != sbWhere && sbWhere.length() > 0) {
            selection = sbWhere.toString();
        }

        int result = database.delete(TAB_NAME, selection, null);
        database.close();
        return result;
    }

    /**
     * 修改下载日志
     * [lpath,sourceId,sstatus,finishTime]
     *
     * @param obj
     * @return
     */
    public int update(DownloadLogEntity obj) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put("lpath", obj.getLpath());
        values.put("sourceId", obj.getSourceId());
        values.put("sstatus", obj.getSstatus());
        values.put("xstatus", obj.getXstatus());
        values.put("finishTime", obj.getFinishTime());
        values.put("sourceFileName", obj.getSourceFileName());
        values.put("address", obj.getAddress());
        String whereClause = " sourceId = ? ";
        String[] whereArgs = new String[]{obj.getSourceId() + ""};
        int result = database.update(TAB_NAME, values, whereClause, whereArgs);
        database.close();
        return result;
    }

    public String getSourceIds() {
        StringBuilder sbSourceIds = new StringBuilder();
        SQLiteDatabase database = dbHelper.getReadableDatabase();

        String orderBy = " _id desc ";
        String selection = null;
        StringBuilder sbWhere = new StringBuilder();
        sbWhere.append(" sstatus in (1,2) ")
                .append(" and sourceId <> '' ");
        if (null != sbWhere && sbWhere.length() > 0) {
            selection = sbWhere.toString();
        }

        Cursor cursor = database.query(TAB_NAME, null, selection, null, null, null,
                orderBy);
        List<DownloadLogEntity> list = new ArrayList<DownloadLogEntity>();
        while (cursor.moveToNext()) {
            Integer sourceId = cursor.getInt(cursor.getColumnIndex("sourceId"));
            if (null == sourceId) continue;
            sbSourceIds.append(sourceId).append(",");
        }
        cursor.close();
        database.close();
        String sourceIds = null;
        if (null != sbSourceIds && sbSourceIds.length() > 0) {
            sourceIds = sbSourceIds.toString();
            sourceIds = sourceIds.substring(0, sourceIds.length() - 1);
        }
        return sourceIds;
    }

    public String getAllSourceIds() {
        StringBuilder sbSourceIds = new StringBuilder();
        SQLiteDatabase database = dbHelper.getReadableDatabase();

        String orderBy = " _id desc ";
        String selection = null;

        Cursor cursor = database.query(TAB_NAME, null, selection, null, null, null,
                orderBy);
        List<DownloadLogEntity> list = new ArrayList<DownloadLogEntity>();
        while (cursor.moveToNext()) {
            Integer sourceId = cursor.getInt(cursor.getColumnIndex("sourceId"));
            if (null == sourceId) continue;
            sbSourceIds.append(sourceId).append(",");
        }
        cursor.close();
        database.close();
        String sourceIds = null;
        if (null != sbSourceIds && sbSourceIds.length() > 0) {
            sourceIds = sbSourceIds.toString();
            sourceIds = sourceIds.substring(0, sourceIds.length() - 1);
        }
        return sourceIds;
    }


    /**
     * 根据资源ID获取下载日志列表信息
     *
     * @return
     */
    public List<DownloadLogEntity> getListBySourceIds(String sourceIds) {
        String selection = null;
        StringBuilder sbWhere = new StringBuilder();
        if (StringHandler.isValidStr(sourceIds)) {
            sbWhere.append(" sourceId in (" + sourceIds + ") and sstatus != '" + BussConstant.SSTATUS_3 + "' ");
            selection = sbWhere.toString();
        }
        return getList(selection);
    }

    /**
     * 获取下载日志列表信息
     *
     * @return
     */
    public List<DownloadLogEntity> getList(String startDate, String endDate) {
        String selection = null;
        StringBuilder sbWhere = new StringBuilder();

        if (StringUtils.isNotEmpty(startDate)) {
            sbWhere.append(" createTime >= '" + startDate + "' ");
        }

        if (StringUtils.isNotEmpty(endDate)) {
            String sigin = " ";
            if (null != sbWhere && sbWhere.length() > 0) {
                sigin = " and ";
            }

            endDate = com.base.common.util.date.DateUtil.getPreDateStr("dd", endDate, -1);
            sbWhere.append(sigin).append(" createTime < '" + endDate + "' ");
        }

        if (null != sbWhere && sbWhere.length() > 0) {
            selection = sbWhere.toString();
        }

        return getList(selection);
    }

    /**
     * 获取过期的广告
     *
     * @return
     */
    public List<DownloadLogEntity> getADExpired() {
        String dateTimeStr = DateUtil.getCurrentDateTime();
        String selection = null;
        StringBuilder sbWhere = new StringBuilder();

        sbWhere.append(" endTime <> ' ' ");
        sbWhere.append(" and endTime <= '" + dateTimeStr + "' ");
        sbWhere.append(" and sstatus = '" + BussConstant.SSTATUS_2 + "' ");

        if (null != sbWhere && sbWhere.length() > 0) {
            selection = sbWhere.toString();
        }

        return getList(selection);
    }

    /**
     * 获取在线的广告
     *
     * @return
     */
    public List<DownloadLogEntity> getADLive() {
        String selection = null;
        StringBuilder sbWhere = new StringBuilder();
        sbWhere.append(" sstatus = '" + BussConstant.SSTATUS_2 + "' ");

        if (null != sbWhere && sbWhere.length() > 0) {
            selection = sbWhere.toString();
        }

        return getList(selection);
    }

    /**
     * 获取在线并且下载完成的广告
     *
     * @return
     */
    public List<DownloadLogEntity> getADLiveAndDownloaded() {
        String selection = null;
        StringBuilder sbWhere = new StringBuilder();
        sbWhere.append(" sstatus = " + BussConstant.SSTATUS_2 + " ");
        sbWhere.append(" and xstatus = " + BussConstant.XSTATUS_2 + " ");

        if (null != sbWhere && sbWhere.length() > 0) {
            selection = sbWhere.toString();
        }

        return getList(selection);
    }

    /**
     * 获取下载失败的广告
     *
     * @return
     */
    public List<DownloadLogEntity> getADDownloadFailed() {
        String selection = null;
        StringBuilder sbWhere = new StringBuilder();

        sbWhere.append(" xstatus = '" + BussConstant.XSTATUS_3 + "' ");

        if (null != sbWhere && sbWhere.length() > 0) {
            selection = sbWhere.toString();
        }

        return getList(selection);
    }

    /**
     * 获取下载日志列表信息
     *
     * @return
     */
    public DownloadLogEntity getBySourceId(Long sourceId) {
        String selection = " sourceId = '" + sourceId + "' ";
        List<DownloadLogEntity> list = getList(selection);
        return (null == list || list.size() == 0) ? null : list.get(0);
    }

    /**
     * 获取下载日志列表信息
     * @param sourceFileName
     * @return
     */
    public DownloadLogEntity getBySourceName(String sourceFileName) {
        String selection = " sourceFileName = '" + sourceFileName + "' ";
        List<DownloadLogEntity> list = getList(selection);
        return (null == list || list.size() == 0) ? null : list.get(0);
    }

    /**
     * 获取所有下载日志列表信息
     *
     * @return
     */
    public List<DownloadLogEntity> getListAll() {
        List<DownloadLogEntity> list = getList(null);
        return list;
    }


    @NonNull
    private List<DownloadLogEntity> getList(String selection) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        String orderBy = " _id desc ";
        Cursor cursor = database.query(TAB_NAME, null, selection, null, null, null,
                orderBy);
        List<DownloadLogEntity> list = new ArrayList<DownloadLogEntity>();
        while (cursor.moveToNext()) {
            Integer _id = cursor.getInt(cursor.getColumnIndex("_id"));
            Integer btype = cursor.getInt(cursor.getColumnIndex("btype"));
            String fname = cursor.getString(cursor.getColumnIndex("fname"));
            String lpath = cursor.getString(cursor.getColumnIndex("lpath"));
            String durl = cursor.getString(cursor.getColumnIndex("durl"));
            Integer xstatus = cursor.getInt(cursor.getColumnIndex("xstatus"));
            Integer _sourceId = cursor.getInt(cursor.getColumnIndex("sourceId"));

            Integer sstatus = cursor.getInt(cursor.getColumnIndex("sstatus"));
            String createTime = cursor.getString(cursor.getColumnIndex("createTime"));
            String finishTime = cursor.getString(cursor.getColumnIndex("finishTime"));
            String remark = cursor.getString(cursor.getColumnIndex("remark"));
            String sourceFileName = cursor.getString(cursor.getColumnIndex("sourceFileName"));
            String address = cursor.getString(cursor.getColumnIndex("address"));
            String aname = cursor.getString(cursor.getColumnIndex("aname"));
            Long fileSize = cursor.getLong(cursor.getColumnIndex("fileSize"));
            DownloadLogEntity obj = new DownloadLogEntity();
            obj.setId(_id.longValue());
            obj.setBtype(btype);
            obj.setFname(fname);
            obj.setLpath(lpath);
            obj.setDurl(durl);
            obj.setXstatus(xstatus);
            if (null != _sourceId) obj.setSourceId(_sourceId.longValue());
            obj.setSstatus(sstatus);
            obj.setCreateTime(createTime);
            obj.setFinishTime(finishTime);
            obj.setRemark(remark);
            obj.setSourceFileName(sourceFileName);
            obj.setAddress(address);
            obj.setAname(aname);
            obj.setFileSize(fileSize);
            list.add(obj);
        }

        cursor.close();
        database.close();

        return list;
    }
}
